package com.y2w.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.y2w.common.exception.NoStockException;
import com.y2w.common.to.mq.OrderTo;
import com.y2w.common.to.mq.SeckillOrderTo;
import com.y2w.common.utils.R;
import com.y2w.common.vo.MemberRespVo;
import com.y2w.gulimall.order.dao.OrderItemDao;
import com.y2w.gulimall.order.entity.OrderItemEntity;
import com.y2w.gulimall.order.entity.PaymentInfoEntity;
import com.y2w.gulimall.order.feign.CartFeignService;
import com.y2w.gulimall.order.feign.MemberFeignService;
import com.y2w.gulimall.order.feign.ProductFeignService;
import com.y2w.gulimall.order.feign.WmsFeignService;
import com.y2w.gulimall.order.interceptor.LoginUserInterceptor;
import com.y2w.gulimall.order.orderenum.OrderStatusEnum;
import com.y2w.gulimall.order.service.OrderItemService;
import com.y2w.gulimall.order.service.PaymentInfoService;
import com.y2w.gulimall.order.to.OrderCreateTo;
import com.y2w.gulimall.order.vo.*;
//import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.y2w.common.utils.PageUtils;
import com.y2w.common.utils.Query;

import com.y2w.gulimall.order.dao.OrderDao;
import com.y2w.gulimall.order.entity.OrderEntity;
import com.y2w.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import static com.y2w.gulimall.order.constant.OrderConstant.USER_ORDER_TOKEN_PREFIX;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    OrderItemService orderItemService;
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    PaymentInfoService paymentInfoService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 订单确认页返回需要的数据
     *
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();

        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //远程查询所有收货地址列表
            RequestContextHolder.setRequestAttributes(attributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);
        }, executor);
        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //远程查询购物车所有选中的购物项
            RequestContextHolder.setRequestAttributes(attributes);
            List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(cartItems);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R r = wmsFeignService.getSkusHasStock(collect);
            if (r.getCode() == 0) {
                List<SkuStockVo> data = r.getData(new TypeReference<List<SkuStockVo>>() {
                });
                if (data != null) {
                    Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                    confirmVo.setStocks(map);
                }
            }
        }, executor);

        //用户积分
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);
        CompletableFuture.allOf(getAddressFuture, cartFuture).get();
        //其他数据
        //防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);
        return confirmVo;
    }

    //@GlobalTransactional 高并发不适合
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        confirmVoThreadLocal.set(vo);
        try {
            SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
            //验证令牌[令牌的对比和删除必须保证原子性]
            String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
            MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

            responseVo.setCode(0);
            String orderToken = vo.getOrderToken();
            if (orderToken != null) {
                Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
                if (result == 0L) {
                    responseVo.setCode(1);
                    return responseVo;
                } else {
                    //下单：去创建订单，验令牌，验价格，锁库存
                    OrderCreateTo order = createOrder();
                //    验价
                    BigDecimal payAmount = order.getOrder().getPayAmount();
                    BigDecimal payPrice = vo.getPayPrice();
                    if(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
                    //    金额对比
                    //TODO    保存订单
                        saveOrder(order);
                    //    库存锁定，有异常就回滚
                        WareSkuLockVo lockVo=new WareSkuLockVo();
                        lockVo.setOrderSn(order.getOrder().getOrderSn());
                        List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                            OrderItemVo orderItemVo = new OrderItemVo();
                            orderItemVo.setSkuId(item.getSkuId());
                            orderItemVo.setCount(item.getSkuQuantity());
                            orderItemVo.setTitle(item.getSkuName());
                            return orderItemVo;
                        }).collect(Collectors.toList());
                        lockVo.setLocks(orderItemVos);
                        //TODO 远程锁库存
                        R r = wmsFeignService.orderLockStock(lockVo);
                        if(r.getCode()==0){
                        //    锁成功
                        //    TODO 远程扣减积分
                            responseVo.setOrder(order.getOrder());
                            //TODO 订单创建成功发送消息给MQ
                            rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                            return responseVo;
                        }else {
                        //    锁定失败
                            throw new NoStockException();
                        }
                    }else{
                        responseVo.setCode(2);
                        return responseVo;
                    }
                }
            }
            //String redisToken = redisTemplate.opsForValue().get(USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
            //if(orderToken!=null&&orderToken.equals(redisToken)){
            ////    令牌验证通过
            //    redisTemplate.delete(USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
            //}
            responseVo.setCode(4);
            return responseVo;
        }catch(Exception e){
            throw e;
        }
        finally {
            if(confirmVoThreadLocal.get()!=null){
                confirmVoThreadLocal.remove();
            }
        }
    }

    //获取订单状态
    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;

    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
    //    查询订单状态
        OrderEntity order = this.getById(orderEntity.getId());
    //    关单
        if(order.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()){
            OrderEntity update = new OrderEntity();
            update.setId(order.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(order,orderTo);
        //    发给mq
            try {
                //把奥正消息一定发出去，每条消息做好日志记录（给数据库保存没一个消息的详细信息）
                //定期扫描数据库将失败的消息再发送一遍
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            } catch (AmqpException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取订单信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {

        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);

        payVo.setOut_trade_no(orderSn); //订单号
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                .eq("order_sn", orderSn));
        payVo.setBody(order_sn.get(0).getSkuAttrsVals()); //备注
        payVo.setSubject(order_sn.get(0).getSkuName()); //订单主题
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString()); //订单金额
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId())
                        .orderByDesc("id")
        );
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> entities = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                    .eq("order_sn", order.getOrderSn()));
            order.setItemEntities(entities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);

        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结果
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no()); //支付宝交易号
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        //添加流水信息
        paymentInfoService.save(infoEntity);
        //修改订单状态
        if (vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")) {
        //    支付成功
            String outTradeNo = vo.getOut_trade_no();
            baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());

        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);
    //    保存订单项
        OrderItemEntity orderItemEntity= new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrder.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        //TODO productFeignService.getSpuInfoBySkuId(seckillOrder.getSkuId());
        orderItemEntity.setSkuQuantity(seckillOrder.getNum());
        orderItemEntity.setSkuId(seckillOrder.getSkuId());
        orderItemService.save(orderItemEntity);

    }

    /**
     * 保存订单数据
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setCreateTime(new Date());
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        //TODO seata0.7 不支持saveBatch
        for (OrderItemEntity orderItem : orderItems) {
            orderItemService.save(orderItem);
        }
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        String orderSn = IdWorker.getTimeId();
        //创建订单
        OrderEntity orderEntity = buildOrder(orderSn);

        //订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        //计算积分、价格相关
        computePrice(orderEntity, itemEntities);
        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);
        return createTo;
    }

    //计算价格相关的
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        Integer giftIntegration = 0;
        Integer giftGrowth = 0;
        for (OrderItemEntity entity : itemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            giftGrowth += entity.getGiftGrowth();
            giftIntegration += entity.getGiftIntegration();
        }
        //    订单价格相关
        orderEntity.setTotalAmount(total);
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //打折
        orderEntity.setPromotionAmount(promotion);
        //    优惠券
        orderEntity.setCouponAmount(coupon);
        //    积分
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setGrowth(giftGrowth);
        orderEntity.setIntegration(giftIntegration);
        orderEntity.setDeleteStatus(0);//未删除

    }

    /**
     * 构建订单
     *
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(memberRespVo.getId());
        //获取收货地址信息
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        if (fare.getCode() == 0) {
            FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
            });
            entity.setFreightAmount(fareResp.getFare());
            //设计收货人信息
            entity.setReceiverCity(fareResp.getAddress().getCity());
            entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
            entity.setReceiverName(fareResp.getAddress().getName());
            entity.setReceiverPhone(fareResp.getAddress().getPhone());
            entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
            entity.setReceiverProvince(fareResp.getAddress().getProvince());
            entity.setReceiverRegion(fareResp.getAddress().getRegion());
            entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
            entity.setAutoConfirmDay(7);
        }
        return entity;
    }

    /**
     * 订单项数据
     *
     * @param orderSn
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        List<OrderItemEntity> itemEntities = new ArrayList<>();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            itemEntities = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);

                return itemEntity;
            }).collect(Collectors.toList());
        }
        return itemEntities;
    }

    /**
     * 构建每一个订单项
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        if (r.getCode() == 0) {
            SpuInfoVo spuInfoVo = r.getData(new TypeReference<SpuInfoVo>() {
            });
            itemEntity.setSpuId(spuInfoVo.getId());
            itemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
            itemEntity.setSpuName(spuInfoVo.getSpuName());
            itemEntity.setCategoryId(spuInfoVo.getCatalogId());
        }
        //sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //优惠信息
        //积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().intValue()*cartItem.getCount());
        itemEntity.setGiftIntegration(cartItem.getPrice().intValue()*cartItem.getCount());
        //订单价格
        //促销
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        //优惠券
        itemEntity.setCouponAmount(new BigDecimal("0"));
        //积分
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        BigDecimal amount = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        amount = amount.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getIntegrationAmount())
                .subtract(itemEntity.getPromotionAmount());
        itemEntity.setRealAmount(amount);
        return itemEntity;
    }

}
